package cc.rengu.redp.bizimpl.upmp.controller;


import cc.rengu.redp.bizimpl.bean.LabelValueBean;
import cc.rengu.redp.bizimpl.constant.UpmpConstant;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpOrganization;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpSysParam;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpOrganizationService;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpSysParamService;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpOrganizationVO;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.common.annotation.Log;
import cc.rengu.redp.common.controller.BaseController;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.domain.RedpResponse;
import cc.rengu.redp.common.exception.RedpException;
import cc.rengu.redp.common.utils.EasyExcelUtil;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.common.collect.Lists;
import com.wuwenze.poi.ExcelKit;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author System
 */
@Api(tags = "机构管理")
@RestController
@RequestMapping("/admin/upmporg")
@Slf4j
public class UpmpOrganizationController extends BaseController {

    @Autowired
    private IUpmpSysParamService upmpSysParamService;

    @Autowired
    private IUpmpOrganizationService upmpOrganizationService;

    /**
     * 查询数据列表
     *
     */
    @GetMapping
    @RequiresPermissions("org:list")
    public Map<String, Object> findPageList(UpmpOrganizationVO org, QueryRequest queryRequest) {
        return this.upmpOrganizationService.findOrgTrees(org);
    }

    /**
     * 查询数据列表
     *
     */
    @GetMapping("/detail/{orgId}")
    @RequiresPermissions(value = {"org:update","org:list","org:add","org:delete"},logical = Logical.OR)
    public RedpResponse findDetail(@NotBlank(message = "{required}") @PathVariable String orgId) {
        UpmpOrganization db =  this.upmpOrganizationService.getById(orgId);
        return new RedpResponse().data(db);
    }

    @Log("新增机构")
    @PostMapping
    @RequiresPermissions("org:add")
    public void add(@Valid UpmpOrganizationVO org) throws RedpException {
        try {
            this.upmpOrganizationService.add(org);
        } catch (Exception e) {
            String message = "新增机构失败";
            log.error(message, e);
            throw new RedpException(message);
        }
    }

    @Log("删除机构")
    @DeleteMapping("/{orgIds}")
    @RequiresPermissions("org:delete")
    public RedpResponse delete(@NotBlank(message = "{required}") @PathVariable String orgIds) throws RedpException {
        try {
            String[] ids = orgIds.split(StringPool.COMMA);
            this.upmpOrganizationService.delete(ids);
            return RedpResponse.getInstance().success();
        } catch (Exception e) {
            String message = "删除机构失败:"+e.getMessage();
            log.error(message, e);
            return RedpResponse.getInstance().message(message).failure();
        }
    }

    @Log("修改机构")
    @PutMapping
    @RequiresPermissions("org:update")
    public void update(@Valid UpmpOrganizationVO org) throws RedpException {
        try {
            this.upmpOrganizationService.update(org);
        } catch (Exception e) {
            String message = "修改机构失败";
            log.error(message, e);
            throw new RedpException(message);
        }
    }

    @PostMapping("excel")
    @RequiresPermissions("org:export")
    public void export(UpmpOrganizationVO org, HttpServletResponse response) throws RedpException {
        try {
            List<UpmpOrganization> orgs = this.upmpOrganizationService.findList(org);
            EasyExcelUtil.export(response,orgs, "机构管理" );
            //ExcelKit.$Export(UpmpOrganization.class, response).downXlsx(orgs, false);
        } catch (Exception e) {
            String message = "导出Excel失败";
            log.error(message, e);
            throw new RedpException(message);
        }
    }


    @ApiOperation(value = "获取法人行")
    @GetMapping("getInstList")
    public List<LabelValueBean> getInstList() throws RedpException {
        UpmpSysParam defaultInst = upmpSysParamService.getById(UpmpConstant.DEAFULT_INST_PARAM_ID);
        List<UpmpSysParam> instList = upmpSysParamService.findChildrenByPrimaryKey(UpmpConstant.SYS_INST_PARAM, defaultInst.getInstId(), null);
        List<LabelValueBean> result = Lists.newArrayList();
        LabelValueBean firt = new LabelValueBean("", "请选择");
        result.add(firt);
        instList.forEach(inst -> {
            LabelValueBean labelValueBean = new LabelValueBean(inst.getPrimaryKey(), inst.getPrimaryValue());
            result.add(labelValueBean);
        });
        return result;
    }

    @GetMapping(value = "/instSelect2List")
    @ApiImplicitParam(paramType = "query", name = "q", value = "条件",  dataType = "String")
    public Map<String, Object> instSelect2List(String q) {
        String instId = "";
        UpmpSysParam defaultInst = upmpSysParamService.getById(UpmpConstant.DEAFULT_INST_PARAM_ID);
        UpmpUserInfoVO currentUser = CommonUtils.getCurrentUser(upmpSysParamService);
        if (currentUser.isAdmin()&&StringUtils.isNotBlank(q)) {
            q = q.replaceAll("&amp;", "&");
            String[] param = q.split("&");
            if (null != param && param.length > 0) {
                instId = param[0];
            }
        } else {
            instId = currentUser.getInstId();
        }
        List<UpmpSysParam> dataDictList = new ArrayList<>();
        Map<String, Object> maps = new HashMap<String, Object>();
        Map<String, String> map = new HashMap<String, String>();
        if (Common.isBlank(instId)) {
            dataDictList= upmpSysParamService.findChildrenByPrimaryKey(UpmpConstant.SYS_INST_PARAM, defaultInst.getInstId(), null);
        } else {
            dataDictList = upmpSysParamService.findChildrenByPrimaryKey(UpmpConstant.SYS_INST_PARAM,instId, null);
        }
        List<Object> list = new ArrayList<Object>();
        for (int i = 0; i < dataDictList.size(); i++) {
            UpmpSysParam dataDict = dataDictList.get(i);
            map = new HashMap<String, String>();
            map.put("id", dataDict.getPrimaryKey());
            map.put("name", dataDict.getPrimaryValue());
            //银联机构号
            map.put("cupsNo", dataDict.getSecondaryKey());
            list.add(map);
        }
        maps.put("results", list);
        maps.put("more", false);
        return maps;
    }
}
